package Controller.listeners;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Timer;
import java.util.TimerTask;

import Model.Newtons;
import View.MainView;

public class NewtonsIncreaseListener implements ActionListener {

	private MainView view;
	private Newtons model;
	private int ctr = 0;
	private int max = 0;
	private int truemax = 0;
	
	public NewtonsIncreaseListener(MainView view, Newtons model) {
		this.view = view;
		this.model = model;
		
	}

	@Override
	public void actionPerformed(ActionEvent e) {
		model.clearList();
		model.setValues(view.getNX(), view.getNIteration(), view.getNFunction(), view.getNThreshold());
		model.computeNewtons();
		view.resetNewtons();
		max = model.getxList().size() - 1;
		truemax = model.getTrueXList().size() - 1;

		view.setComputeNewtonsButtonEnabled(false);
		
		final Timer timer = new Timer(); 
		timer.schedule( new TimerTask() {
			public void run() {
				if(ctr <= max)
					view.addNewtonsRow(model.getxList().get(ctr), model.getyList().get(ctr), 
						model.getyPrimeList().get(ctr), model.getThresholdList().get(ctr));	
				if(ctr <= truemax)
					view.addNewtonsList(model.getTrueXList().get(ctr), model.getTrueYList().get(ctr));
				view.updateNewtonsChart();
				ctr++;
				if(ctr >  max && ctr > truemax) {
					if(ctr <= max)
						view.addNewtonsRow(model.getxList().get(ctr), model.getyList().get(ctr), 
							model.getyPrimeList().get(ctr), model.getThresholdList().get(ctr));	
					if(ctr <= truemax)
						view.addNewtonsList(model.getTrueXList().get(ctr), model.getTrueYList().get(ctr));
					view.updateNewtonsChart();
					ctr = 0;
					timer.cancel();
					view.setComputeNewtonsButtonEnabled(true);
				}		
			 } 
		}, 1000, 2000);		
	}
}
